package de.ur.iw.wiki.weighters;

import static de.ur.iw.wiki.Settings.KEY_CATEGORIES_WEIGHT;
import static de.ur.iw.wiki.Settings.KEY_FILES;
import de.ur.iw.wiki.Link;
import de.ur.iw.wiki.LinkInfo;
import de.ur.iw.wiki.Settings;
import de.ur.iw.wiki.Weighter;

public class BasicWeighter implements Weighter {

	public static final int START_POSITION = 33;
	public static final int MIDDLE_POSITION = 67;

	@Override
	public void weight(Link l) {
		double categoryChance = Settings.getDouble(KEY_CATEGORIES_WEIGHT, 0);
		String type = l.getInfo().getString(LinkInfo.KEY_TYPE);

		double weight = 0;

		double weightOfParagraph = getWeightOfParagraphPosition(l);
		double weightOfLink = getWeightOfLinkPosition(l);

		weight = weightOfParagraph * weightOfLink;

		if (type.equals(LinkInfo.VAL_CATEGORY)) {
			weight *= (categoryChance);
		} else if (type.equals(LinkInfo.VAL_FILE)) {
			boolean useFiles = Settings.getBoolean(KEY_FILES, false);
			weight *= (useFiles ? 1 - categoryChance : 0);
		} else {
			weight *= (1 - categoryChance);
		}

		l.setWeight(weight);
	}

	private double getWeightOfLinkPosition(Link l) {
		int pos = l.getInfo().getInt(LinkInfo.KEY_POSITION_IN_PARAGRAPH);
		if (pos <= START_POSITION) {
			return Settings
					.getDouble(Settings.KEY_WEIGHT_OF_FIRST_LINKS, 1);
		} else if (pos > MIDDLE_POSITION) {
			return Settings.getDouble(Settings.KEY_WEIGHT_OF_LAST_LINKS, 1);
		} else {
			return Settings.getDouble(Settings.KEY_WEIGHT_OF_MIDDLE_LINKS,
					1);
		}
	}

	private double getWeightOfParagraphPosition(Link l) {
		int pos = l.getInfo().getInt(LinkInfo.KEY_POSITION_OF_PARAGRAPH);
		if (pos <= START_POSITION) {
			return Settings.getDouble(Settings.KEY_WEIGHT_OF_FIRST_PARAGRAPHS, 1);
		} else if (pos > MIDDLE_POSITION) {
			return Settings.getDouble(Settings.KEY_WEIGHT_OF_LAST_PARAGRAPHS, 1);
		} else {
			return Settings.getDouble(Settings.KEY_WEIGHT_OF_MIDDLE_PARAGRAPHS, 1);
		}
	}

}
